import config from '../config/config.js'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast,toastload,closeload, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
  // 是否需要设置 token
  toastload()
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
    // config.header['Content-Type'] = 'application/json'
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
    uni.request({
        method: config.method || 'get',
        timeout: config.timeout ||  timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      }).then(res => {
		  closeload()
        const code = res.data.error_code || 200
        const msg = errorCode[code] || res.data.message || errorCode['default']
        if (code === 401||res.data.error_code==401) {
			console.log("报错请求res",res);
			let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
			let curRoute = routes[routes.length - 1].route // 获取当前页面路由，也就是最后一个打开的页面路由
			if(curRoute != 'pages/index/login'){
				showConfirm('登录状态已过期，请重新登录?').then(res => {
				  if (res.confirm) {
					  // #ifdef MP-WEIXIN
					  uni.navigateTo({
					  	url: '/pages/wx-login/wx-login'
					  })
					  //  #endif
					  // #ifdef APP||H5
					  uni.navigateTo({
					  	url: '/page/login/login'
					  })
					  //  #endif
				  }
				})
				reject('请重新登录。')
			}
        } else if (code === 500) {
          toast(msg)
          reject('500')
        } else if (code !== 200) {
          toast(msg)
          reject(code)
        }
        resolve(res.data)
      })
      .catch(error => {
        let { errMsg } = error
		console.log("错误",errMsg);
        if (errMsg === 'request:fail ') {
          errMsg = '网络异常'
        } else if (errMsg.includes('request:fail timeout')) {
          errMsg = '网络异常'
        } else if (errMsg.includes('Request failed with status code')) {
		  errMsg = '网络异常'
        }
        toast(errMsg)
        reject(error)
      })
  })
}

export default request